<template>
  <div class="chat-app">
    <el-row class="chat-row">
      <!-- 左侧好友列表 -->
      <el-col :span="6" class="sidebar">
    <div class="chat-header" >当前登录的账号名称：{{currentLoginUserName}}</div>
        <div class="online-users">
          <h3>在线用户</h3>
          <ul>
            <li
              v-for="user in onlineUser"
              :key="user.id"
              @click="selectUser(user.id)"
              :class="{ selected: user.id === selectUserId }"
            >
              <img :src="user.img" alt="头像" />
              <span>{{ user.name }}</span>
            </li>
          </ul>
        </div>
      </el-col>

      <!-- 右侧聊天区 -->
      <el-col :span="18" class="chat-area">
        <!-- 登录者名字显示在顶部 -->
        <div class="chat-header">
          <span class="current-user-name">{{ currentUserName }}</span>
        </div>

        <div class="chat-box">
          <div class="messages" ref="messages">
            <div
              v-for="(msg, index) in messages"
              :key="msg.id"
              :class="[ 'message', msg.sendUserId === currentUserId ? 'me' : 'other']"
            >
              <strong>{{ msg.sendUserId }}:</strong>
              <span>{{ msg.content }}</span>
            </div>
          </div>
        </div>

        <div class="input-area">
          <input
            v-model="message.content"
            type="text"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
          />
          <button @click="sendMessage">发送</button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { websocketObj } from "../utils/websocket"; // 引入 WebSocket 工具
import {
  getOnlineUserList,
  getUserNameById,
  getHistoryMsg,
  getUserInfoByToken,
  sendChatMsg,
} from "../apis/message"; // 引入接口

export default {
  name: "ChatApp",
  data() {
    return {
      onlineUser: [], // 在线用户列表
      messages: [], // 聊天记录
      message: { content: "", receiveUserId: "" }, // 当前消息输入
      currentUserName: "", // 当前选中聊天用户名称
      selectUserId: null, // 当前选中的用户ID
      token: "", // 当前用户 token
      currentUserId: "", // 当前登录用户ID
      currentLoginUserName:"", // 当前登录用户名称

    };
  },
  created() {
    this.token = sessionStorage.getItem("token");
    if (this.token) {
      this.getUserInfo(this.token);
      this.initWebSocket(this.token);
    }
    this.queryOnlineUser();
  },
  destroyed() {
    websocketObj.stop(); // 销毁 WebSocket 连接
  },
  methods: {
    // 根据登录成功后获取的token，来获取用户信息
    getUserInfo(token) {
      getUserInfoByToken(token)
        .then((res) => {
          this.currentUserId = res.data.id;
          this.currentLoginUserName = res.data.name;
          sessionStorage.setItem("currentUserId", this.currentUserId);
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
        });
    },
    // 查询在线用户
    queryOnlineUser() {
      getOnlineUserList()
        .then((res) => {
          this.onlineUser = res.data.map((user) => ({
            id: user.id,
            name: user.name,
            img: user.img,
          }));
        })
        .catch((error) => {
          console.error("获取在线用户失败:", error);
        });
    },

    // 选择聊天用户
    selectUser(receiveUserId) {
      this.selectUserId = receiveUserId; // 仅更新聊天对象的 ID
      this.loadMessages(receiveUserId); // 加载聊天记录
      getUserNameById(receiveUserId)
        .then((res) => {
          this.currentUserName = res.data.name;
        })
        .catch((error) => {
          console.error("获取用户名称失败:", error);
        });
    },

    // 加载消息
    loadMessages(receiveUserId) {
      getHistoryMsg(receiveUserId)
        .then((res) => {
          this.messages = res.data.map((msg) => ({
            ...msg,
            formattedTime: new Date(msg.sendTime).toLocaleString(),
          }));
        })
        .catch((error) => {
          console.error("获取历史记录失败:", error);
        });
    },

    // 发送消息
    sendMessage() {
      if (this.message.content.trim() !== "") {
        sendChatMsg(this.selectUserId, this.message.content).then((res) => {
          if (res.code === 200) {
            this.messages.push({
              sendUserId: this.currentUserId,
              receiveUserId: this.selectUserId,
              content: this.message.content,
            });
            this.message.content = ""; // 清空输入框
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } else {
            alert("发送失败");
          }
        });
      }
    },

    // WebSocket 接收到消息时的处理
    websocketonmessage(data) {
      if (data && data.sendUserId && data.content) {
        this.messages.push({
          sendUserId: data.sendUserId,
          receiveUserId: data.receiveUserId,
          content: data.content,
        });
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },

    // 滚动到聊天框底部
    scrollToBottom() {
      this.$refs.messages.scrollTop = this.$refs.messages.scrollHeight;
    },

    // 初始化 WebSocket 连接
    initWebSocket(token) {
      websocketObj.socket((data) => {
        this.websocketonmessage(data);
      });
    },
  },
};
</script>

<style scoped>
/* 样式部分 */
.chat-app {
  display: flex;
  height: 100vh;
  flex-direction: row;
}

.chat-row {
  flex: 1;
  display: flex;
}

.sidebar {
  background-color: #f8f8f8;
  padding: 10px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  width: 300px;
}

.online-users {
  font-size: 14px;
}

.online-users h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
}

.online-users ul {
  padding: 0;
  list-style-type: none;
}

.online-users li {
  padding: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.online-users li:hover {
  background-color: #e9f5ff;
}

.online-users li.selected {
  background-color: #d0e7ff;
}

.online-users img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.chat-header {
  background-color: #3b8ad9;
  padding: 15px;
  font-size: 20px;
  color: white;
  text-align: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.current-user-name {
  font-weight: bold;
  font-size: 18px;
}

.chat-box {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
}

.messages {
  margin-bottom: 20px;
}

.message {
  padding: 10px;
  border-radius: 10px;
  max-width: 70%;
  word-wrap: break-word;
  margin-bottom: 10px;
}

.message.me {
  background-color: #d1f5d3;
  align-self: flex-end;
  text-align: right;
}

.message.other {
  background-color: #f1f1f1;
  align-self: flex-start;
}

.message strong {
  font-weight: bold;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.input-area input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
}

.input-area button {
  padding: 10px 20px;
  background-color: #3b8ad9;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
}

.input-area button:hover {
  background-color: #1f6fa2;
}
</style>
